package com.zbkj.admin.filter;

import cn.hutool.core.util.ObjectUtil;
import com.zbkj.common.token.AdminTokenComponent;
import com.zbkj.common.vo.LoginUserVo;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器
 * 1、验证token有效性
 * 2、只执行一次过滤，可用于防止重复提交
 * 3、用于Spring Security 用户名密码认证信息设置
 * @author lijie
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private AdminTokenComponent tokenComponent;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        //获取-登录的管理员用户信息
        LoginUserVo loginUser = tokenComponent.getLoginAdminUser(request);
        if (ObjectUtil.isNotNull(loginUser)) {
            //验证并刷新token
            tokenComponent.verifyToken(loginUser);
            //Spring Security 用户名密码认证信息
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    loginUser,
                    null,
                    loginUser.getAuthorities());
            //设置请求到认证
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //将authentication信息放入到上下文对象中
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
